require 'osx/cocoa'
require 'renderers/cocoa'
include OSX

class STMainView < NSView
  include ConversionHelpers
  
  ib_outlets :controller, :selected_object_name
  
  attr_accessor :timer, :renderer
  attr_reader :selected_object
  
  def initialize
    @keys = {
      KEY_LEFT_ARROW => false,
      KEY_RIGHT_ARROW => false,
      KEY_UP_ARROW => false,
      KEY_DOWN_ARROW => false
    }
    
    @renderer = CocoaRenderer.new
  end
  
  def awakeFromNib
    @timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
      1.0/60.0, self, :tick, nil, true
    )
    
    @controller.views << self
  end
  
  def update
    setNeedsDisplay(true)
  end
  
  def drawRect(rect)
    drawSpace
    drawObjects
    if @controller.game.paused?
      drawPaused
    end
  end
  
  def drawSpace
    NSColor.blackColor.set
    NSRectFill(bounds)
  end
  
  def drawObjects
    @controller.game.objects.each { |o| @renderer.render(o) }
  end
  
  def createFont
    if @font.nil?
      @font = NSMutableDictionary.alloc.init
      @font.setObject_forKey(NSFont.fontWithName_size("Helvetica", 30), NSFontAttributeName)
      @font.setObject_forKey(NSColor.whiteColor, NSForegroundColorAttributeName)
    end
    
    @font
  end
  
  def drawPaused
    # Draws a 90% black rect over the whole screen, causing the game to appear faded.
    NSColor.blackColor.colorWithAlphaComponent(0.9).set
    NSRectFillUsingOperation(bounds, NSCompositeSourceOver)
    
    createFont
    pos = NSPoint.new(bounds.origin.x + (bounds.size.width - size.width) / 2, bounds.origin.y + (bounds.size.height - size.height) / 2)
    size = NSString.stringWithString("Paused").sizeWithAttributes(@font)
    string.drawAtPoint_withAttributes(pos, @font)
  end
  
  def selected_object=(obj)
    @selected_object = obj
    @selected_object_name.stringValue = obj.nil? ? "Nothing" : obj.name
  end
  
  def tick
    @controller.tick
  end
  
  def acceptsFirstResponder
    true
  end
  
  def keyDown(event)
    @controller.keyDown(event)
  end
  
  def keyUp(event)
    @controller.keyUp(event)
  end
  
  def mouseDown(event)
    location = event.locationInWindow
    location = convertPoint_fromView(location, nil)
    point = NSPointToPoint(location)
    
    object_selected = false
    @controller.game.objects.each do |o|
      if o.hit?(point)
        object_selected = true
        self.selected_object = o
        break
      end
    end
    
    self.selected_object = nil unless object_selected
  end
  
  ib_action :fullscreen do |sender|
    if isInFullScreenMode
      exitFullScreenModeWithOptions(NSDictionary.alloc.init)
    else
      enterFullScreenMode_withOptions(NSScreen.mainScreen, NSDictionary.alloc.init)
    end
    
    sender.state = isInFullScreenMode ? NSOnState : NSOffState
  end
end